package cn.xuchunh.campusbbs.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.widget.TextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.xuchunh.campusbbs.R;
import pl.droidsonroids.gif.GifDrawable;

/**
 * Created by XuChunH on 2015/9/17.
 */
public class AdvancedTextView extends TextView {

    private SparseArray<GifRequester> gifHandlerSparseArray;
    private int gifCount;
    private String imagePattern, imageSrcPattern;
    private SpannableStringBuilder stringBuilder;


    public AdvancedTextView(Context context) {
        super(context);
        init();
    }

    public AdvancedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();

    }

    public AdvancedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public AdvancedTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();

    }

    private void init() {
        gifHandlerSparseArray = new SparseArray<>();
        gifCount = 0;
        imagePattern = "(?m)\\[mobcent_phiz=.*?\\]";
        imageSrcPattern = "http:(.*/)*/.*\\.\\w+";
    }


    public synchronized void notifyGifRequestFinished(int id) {
        if (gifCount <= 0 || stringBuilder == null) {
            return;
        }
        gifCount--;
        GifRequester gifRequester = gifHandlerSparseArray.get(id);
        if (gifRequester != null) {
            GifDrawable mGifDrawable = gifRequester.getGifDrawable();
            if (mGifDrawable != null && !mGifDrawable.isRecycled()) {
                stringBuilder.setSpan(new ImageSpan(mGifDrawable), gifRequester.getStart(), gifRequester.getEnd(), 0);
                setText(stringBuilder);
//                postInvalidate();
            }
        }

    }

    public void setRichText(CharSequence text) {
        close();
        Matcher matcher = Pattern.compile(imagePattern).matcher(text);
        Drawable drawable = getResources().getDrawable(R.color.grey_400);
        stringBuilder = new SpannableStringBuilder(text);
        while (matcher.find()) {
            GifRequester gifRequester = new GifRequester(this);
            gifRequester.setId(gifCount);
            gifRequester.setStart(matcher.start());
            gifRequester.setEnd(matcher.end());
            gifHandlerSparseArray.put(gifCount, gifRequester);
            gifCount++;
            Matcher uriMatcher = Pattern.compile(imageSrcPattern).matcher(matcher.group());
            if (uriMatcher.find()) {
                stringBuilder.setSpan(new ImageSpan(drawable), matcher.start(), matcher.end(), 0);
                gifRequester.setImageUri(Uri.parse(uriMatcher.group()));
            } else {
                gifCount--;
                gifHandlerSparseArray.remove(gifCount);
            }
        }
        setText(stringBuilder);

    }

    @Override
    protected void onDetachedFromWindow() {
        int size = gifHandlerSparseArray.size();
        for (int i = 0; i < size; i++) {
            GifRequester gifRequester = gifHandlerSparseArray.get(i);
            gifRequester.getDraweeHolder().onDetach();
        }
        close();
        super.onDetachedFromWindow();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        int size = gifHandlerSparseArray.size();
        for (int i = 0; i < size; i++) {
            GifRequester gifRequester = gifHandlerSparseArray.get(i);
            gifRequester.getDraweeHolder().onAttach();
        }
    }

    @Override
    public void onStartTemporaryDetach() {
        super.onStartTemporaryDetach();
        int size = gifHandlerSparseArray.size();
        for (int i = 0; i < size; i++) {
            GifRequester gifRequester = gifHandlerSparseArray.get(i);
            gifRequester.getDraweeHolder().onDetach();
        }
    }

    @Override
    public void onFinishTemporaryDetach() {
        super.onFinishTemporaryDetach();
        int size = gifHandlerSparseArray.size();
        for (int i = 0; i < size; i++) {
            GifRequester gifRequester = gifHandlerSparseArray.get(i);
            gifRequester.getDraweeHolder().onAttach();
        }
    }

    private void close() {
        try {
            int size = gifHandlerSparseArray.size();
            if (stringBuilder != null) {
                stringBuilder.clear();
                stringBuilder = null;
            }
//            for (int i = 0; i < size; i++) {
//                GifRequester gifRequester = gifHandlerSparseArray.get(i);
//                GifDrawable mGifDrawable = gifRequester.getGifDrawable();
//                if (mGifDrawable != null && !mGifDrawable.isRecycled()) {
//                    mGifDrawable.recycle();
//                }
//            }
            gifHandlerSparseArray.clear();
            gifCount = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
